<template>
  <div class="box">
    <NavBar title="登录" />
    <van-cell-group style="margin-top: 20px" inset>
      <h1>登录/注册</h1>
      <van-field
        v-model="tel"
        label="+86"
        type="tel"
        placeholder="请输入手机号"
      />
      <van-field
        v-model="telCode"
        type="number"
        center
        clearable
        placeholder="请输入短信验证码"
      >
        <template #button>
          <van-button
            style="background-color: #f1f1f1; border: none"
            size="small"
            @click="getImgCode()"
            type="default"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <van-button
        style="background-color: #1ec7af; font-size: 16px"
        class="btn"
        type="primary"
        block
        @click="loginFn"
        >登录/注册</van-button
      >
    </van-cell-group>

    <div class="xx">点击按钮表示同意<span>《蘑菇宠医服务协议》</span></div>

    <!-- 图形验证码弹窗 -->
    <van-dialog
      v-model:show="show"
      title="请完成验证码"
      show-cancel-button
      @confirm="sendMsg"
      ><p>
        <input type="text" v-model="imgCode" class="sr" />
        <img class="yzImg" :src="imgBase64" />
      </p>
    </van-dialog>
  </div>
</template>
<script setup>
import { showSuccessToast, showFailToast } from "vant";
import { getKeyImg, sendLogin, login } from "../API";
import NavBar from "../components/NavBar.vue";
import { useRouter } from "vue-router";
let router = useRouter();
import { ref } from "vue";
let tel = ref(""); //手机号
let telCode = ref(""); //短信验证码
let imgCode = ref(""); //图形验证码
let imgBase64 = ref(""); //图片base64
let key = ""; //图形验证码的key
let show = ref(false);
// 请求图形验证码
let getImgCode = async () => {
  let r = await getKeyImg();
  // console.log(r.data);
  key = r.data.data.key;
  imgBase64.value = r.data.data.img;
  // console.log(imgBase64.value);
  if (imgBase64.value.length > 0) {
    show.value = true;
  }
};
// getImgCode();
// 发送短信验证码
let sendMsg = async () => {
  let r = await sendLogin({
    captcha_code: imgCode.value,
    captcha_key: key,
    phone: tel.value,
  });
  if (r.data.data.code == 200) {
    showSuccessToast(r.data.data.message);
  } else {
    showFailToast(r.data.data.message);
  }
  // 清空
  imgBase64.value = key = "";
};

// 登录 注册
let loginFn = async () => {
  let r = await login({
    code: telCode.value,
    phone: tel.value,
  });
  // console.log(r.data);
  if (r.data.code == 200) {
    console.log("登陆成功");
    localStorage.setItem("token", r.data.data.access_token);
    router.replace("/index");
  } else {
    console.log("手机或验证码错误");
  }
};
</script>
<style scoped>
.box {
  width: 100%;
  padding: 0 10px;
  box-sizing: border-box;
}
.sr {
  width: 60%;
  height: 80px;
  margin: 10px 20px;
  float: left;
}
.yzImg {
  width: 30%;
  height: 80px;
  margin-top: 15px;
}
.btn {
  margin: 40px 0 20px;
}
.xx {
  margin: 0 40px;
  font-size: 27px;
  color: #999;
}
span {
  color: #1ec7af;
}
</style>
